/* http请求
 * HttpUtil.js
 */
import {showMessagePopup} from '../utils/H5helper';

export function postFormData(url,params){
	//if(__DEV__) console.log('提交的参数值：'+JSON.stringify(params));
	let formData=new FormData();
	for(let name in params){
		if(params[name]!=null) 
			formData.append(name, params[name]);
	}
	return fetchPost(url,formData);
}

export function uploadFiles(url,files,params){
	let formData=new FormData();
	for(let name in params){
		if(params[name]!=null) 
			formData.append(name, params[name]);
	}
	for(let name in files){
		if(files[name]!=null) 
			formData.append("file[]", files[name]);
	}
	return fetchPost(url,formData);
}

export function getData(url,params=null){
	//if(__DEV__) console.log('提交的参数值：'+JSON.stringify(params));
	return postFormData(url,params);
	/*const url_new=create_url(url,params);
	console.log(getCookie('ticket'));
	return fetch(url_new, {
			method: "GET",
			mode: 'cors',//跨域请求
        	credentials: 'include'//包含cookie
		})
		.then(response=> {
			return response.json();
		},error=>{
			console.log('fetch get data error');
			console.log(error);
		})
		.then(res=>{
			if(res.code!=200){//session过期或者未登录
				showMessagePopup(res.message);
			}else{
				return res;
			}
		});*/
}

function fetchPost(url,formData){
	const ticket=getCookie('ticket');
	formData.append('ticket', ticket);
	return fetch(url, {
			mode: 'cors',//跨域请求
        	//credentials: 'include',//包含cookie
			method: 'POST',
			body: formData
		}).then(response=> {
			return response.json();
		},error=>{
			console.log('fetch upload file error');
			console.log(error);
		}).then(res=>{
			if(res.code!=200){//session过期或者未登录
				showMessagePopup(res.message);
			}else{
				return res;
			}
		});
}

/*
function create_url(url,params){
	const contactChar=_.includes(url, '?')?'&':'?';
	const timestamp=new Date().getTime();
	let urlPath=url+contactChar+'time='+timestamp+'&ticket='+getCookie('ticket');
	if(params!=null){
		for(let name in params){
			if(params[name]!=null)
				urlPath=urlPath+'&'+name+'='+params[name];
		}
	}
	return urlPath;
}*/

function getCookie(name){
	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	if(arr=document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
}